package com.cuz.for2024;

import java.lang.reflect.Array;
import java.util.Arrays;

public class T322 {
    public int coinChange(int[] coins, int amount) {
        if (coins == null || coins.length == 0 || amount < 0) {
            return -1;
        }

        Arrays.sort(coins);
        int[] cache = new int[amount + 1];
        Arrays.fill(cache, -1);
        return func(coins, coins.length - 1, amount, cache);
    }

    private int func(int[] coins, int start, int left, int[] cache) {
        if (left == 0) {
            return 0;
        }
        if (start < 0) {
            return -1;
        }

        int min = -1;
        for (int count = 0; coins[start] <= left; count++) {
            int now = coins[start];
            left = left - now * count;
            if (left<0){
                continue;
            }
            int cached = cache[left];

            int r = cached != -1 ? cached : func(coins, start - 1, left, cache);
            cache[left] = r;
            if (r == -1) {
                continue;
            }
            int temp = r + count;

            min = min == -1 ? temp : Math.min(min, temp);
        }
        return min;
    }

    public static void main(String[] args) {
        System.out.println(new T322().coinChange(new int[]{1}, 2));
    }
}
